package cn.ilikes.tools.nosql.jpa.configs.indexs;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;

public class DefaultPaserConfigs implements PaserConfigs {

	private Logger logger = Loggerfactory.instance(DefaultPaserConfigs.class);

	public IndexConfigs paserConfigs(URL url) throws IndexRunTimeException {
		Loggerfactory.info(logger, "start paser index  configs : " + url.getFile());
		InputStream in = null;
		try {
			URLConnection uc = url.openConnection();
			in = uc.getInputStream();
			IndexConfigs indexConfigs = paser(in);
			return indexConfigs;
		} catch (IOException e) {
			throw new IndexRunTimeException(e);
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	private IndexConfigs paser(InputStream in) {
		IndexConfigs dataStore = new IndexConfigs();
		SAXReader saxReader = new SAXReader();
		try {
			Document doc = saxReader.read(in);
			Element root = doc.getRootElement();
			for (Iterator<Element> iter = root.elementIterator(); iter.hasNext();) {
				Element element = iter.next();
				if (element.getName().equals("name")) {
					String name = element.getText();
					dataStore.setName(name);
					if (Loggerfactory.isdebug(logger))
						Loggerfactory.debug(logger, "paser index configs   name  : " + name);
				} else if (element.getName().equals("type")) {
					String type = element.getText();
					dataStore.setType(type);
					if (Loggerfactory.isdebug(logger))
						Loggerfactory.debug(logger, "paser index configs   type  : " + type);
				} else

				if (element.getName().equals("properties")) {

					for (Iterator<Element> propertiesElements = element.elementIterator(); propertiesElements.hasNext();) {
						Element propertiesElement = propertiesElements.next();
						String propertiesName = propertiesElement.attributeValue("name");
						String value = propertiesElement.attributeValue("value");
						if (Loggerfactory.isdebug(logger))
							Loggerfactory.debug(logger, "paser index configs   propertiesName : " + propertiesName + "  value : " + value);
						dataStore.getProperties().put(propertiesName, value);
					}

				}

			}
			return dataStore;
		} catch (DocumentException e) {
			Loggerfactory.error(logger, "paser index configs  no success .");
			throw new IndexRunTimeException("paser index configs  no success .", e);
		}

	}
}
